package com.yh.correct.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.web.session.HttpServletSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.yh.common.utils.DateUtils;
import com.yh.common.utils.ExcelUtil;
import com.yh.correct.model.Condition;
import com.yh.correct.model.CorrectedPerson;
import com.yh.correct.model.MonthTest;
import com.yh.correct.model.Page;
import com.yh.correct.model.ResultData;
import com.yh.correct.service.ICorrectedPersonService;
import com.yh.correct.service.IMonthTestService;

/**
 * @author 刘文涛 E-mail: 894516860@qq.com
 * @version 创建时间：2017年3月10日 上午10:57:08 月度考核记录模型控制器
 */
@RestController
@RequestMapping(value = "/monthtest")
public class MonthTestController {
	/**
	 * 日志记录
	 */
	private static Logger logger = LogManager.getLogger(MonthTestController.class);
	/**
	 * 注入月度考核业务服务
	 */
	@Autowired
	private IMonthTestService monthtestservice;
	@Autowired
	private ICorrectedPersonService correctedPersonService;

	/**
	 * 模糊查询 查询条件(矫正单位,服刑人员,考核月度,考核等级)
	 * 
	 * @return
	 */
	@RequestMapping(value = "/querylike")
	public Page queryLikeMonthTest(HttpServletRequest request, int pageSize, int pageNum, Condition condition) {
		logger.info("查询月度考核记录条件" + condition);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("pageSize", pageSize);
		map.put("pageNum", pageNum);
		map.put("cunit", condition.getCunit());
		map.put("cname", condition.getCname());
		if (!"".equals(condition.getCdate())) {
			map.put("month", condition.getCdate());
		}
		if (!"".equals(condition.getCclazz())) {
			map.put("clazz", condition.getCclazz());
		}
		Page page = monthtestservice.getLikeMonthTest(map);
		request.setAttribute("page", page.getResult());
		return page;
	}

	/**
	 * 获取月度考核详情
	 * 
	 * @param request
	 * @param monthtest
	 * @return
	 */
	@RequestMapping(value = "/detail")
	public ModelAndView getDetail(HttpServletRequest request, MonthTest monthtest, String sort) {
		Map<String, Object> m = monthtestservice.getMonthTestById(monthtest);
		Map<String, Object> rsMap = new HashMap<String, Object>();
		Map<String, Object> mm = new HashMap<String, Object>();
		List<Map<String, Object>> list1 = monthtestservice.selectLabourList(m);
		List<Map<String, Object>> list2 = monthtestservice.selectReportList(m);
		List<Map<String, Object>> list3 = monthtestservice.selectThoughtList(m);
		List<Map<String, Object>> list4 = monthtestservice.selectPointsList(m);
		List<Map<String, Object>> list5 = monthtestservice.selectBonusList(m);
		rsMap.put("details", m);
		rsMap.put("labour", list1);
		rsMap.put("report", list2);
		rsMap.put("thought", list3);
		rsMap.put("points", list4);
		rsMap.put("bonus", list5);
		logger.info("查看月度考核详情" + m.toString());
		if ("check".equals(sort)) {
			return new ModelAndView("examine/monthtest_check", rsMap);
		}
		return new ModelAndView("examine/monthtest_edit", rsMap);
	}

	/**
	 * 增加月度考核记录
	 * 
	 * @param monthtest
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "/addMonthTest")
	public ResultData addRuleBreak(MonthTest monthtest) {
		logger.info("增加月度考核记录" + monthtest.toString());
		int i=monthtestservice.addMonthTest(monthtest);
		ResultData resultdata=new ResultData();
		if(i>0){
			resultdata.setCode(4000);
			resultdata.setMessage("增加成功");
		}else{
			resultdata.setCode(4001);
			resultdata.setMessage("增加失败");
		}
		return resultdata;
	}

	/**
	 * 删除月度考核记录
	 * 
	 * @param monthtest
	 * @return
	 */
	@RequestMapping(value = "/delMonthTest")
	public ResultData delMonthTest(MonthTest monthtest) {
		logger.info("删除月度考核记录id=" + monthtest.getId());
		int i=monthtestservice.delMonthTest(monthtest);
		ResultData resultdata=new ResultData();
		if(i>0){
			resultdata.setCode(4000);
			resultdata.setMessage("删除成功");
		}else{
			resultdata.setCode(4001);
			resultdata.setMessage("删除失败");
		}
		return resultdata;
	}

	/**
	 * 修改月度考核记录
	 * 
	 * @param monthtest
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "/updateMonthTest")
	public ResultData updateMonthTest(MonthTest monthtest) {
		logger.info("修改月度考核记录id=" + monthtest.toString());
		int i=monthtestservice.updateMonthTest(monthtest);
		ResultData resultdata=new ResultData();
		if(i>0){
			resultdata.setCode(4000);
			resultdata.setMessage("修改成功");
		}else{
			resultdata.setCode(4001);
			resultdata.setMessage("修改失败");
		}
		return resultdata;
	}

	/**
	 * tree点击返回url
	 * 
	 * @return
	 */
	@RequestMapping(value = "/url")
	public ModelAndView getUrl() {
		return new ModelAndView("examine/monthtest");
	}

	/**
	 * 根据月度考核记录id批量删除
	 * 
	 * @param id
	 */
	@RequestMapping(value = "/getDeleteIds")
	public void getDeleteIds(int[] id) {
		MonthTest monthtest = new MonthTest();
		for (int i : id) {
			logger.info("批量删除月度考核id=" + i);
			monthtest.setId(i);
			monthtestservice.delMonthTest(monthtest);
		}
	}

	/**
	 * 月底自动生成月度考核记录
	 * ("0 30 23 L * ?")表示每个月的最后一天的23点30分执行
	 * @Scheduled(cron = "0/10 * * * * ? ")//测试从第0秒开始.每个十秒触发一次
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/auto")
	
	public void auto() throws Exception {
		List<CorrectedPerson> list = correctedPersonService.findCorrectedPerson();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		//定义本月的公益劳动、思想教育、思想汇报的总次数times，每次10分,可算出每个月的基准分
		int times = monthtestservice.selectLabourTimes(sdf.format(new Date()))
				+ monthtestservice.selectReportTimes(sdf.format(new Date()))
				+ monthtestservice.selectThoughtTimes(sdf.format(new Date()));
		for (CorrectedPerson correctedPerson : list) {
			MonthTest monthtest = new MonthTest();
			Map<String, Object> m = new HashMap<String, Object>();
			m.put("pid", correctedPerson.getId());
			m.put("date", sdf.format(new Date()));
			if (monthtestservice.selectIsExist(m) == 0) {// 如果不存在记录就增加月度考核记录,如果存在就不添加
				// 根据pid和月份查找公益劳动列表
				List<Map<String, Object>> listlabour = monthtestservice.selectLabourList(m);
				// 获取公益劳动的总分
				int labourscore = 0;
				if (listlabour != null) {
					for (Map<String, Object> map : listlabour) {
						labourscore += (int) map.get("score");
					}
				}
				logger.info("labourscore=" + labourscore);
				// 根据pid和月份查找思想汇报列表
				List<Map<String, Object>> listreport = monthtestservice.selectReportList(m);
				// 获取思想汇报的总分
				int reportscore = 0;
				if (listreport != null) {
					for (Map<String, Object> map : listreport) {
						reportscore += (int) map.get("score");
					}
				}
				logger.info("reportscore=" + reportscore);
				// 根据pid和月份查找集中学习列表
				List<Map<String, Object>> listthought = monthtestservice.selectThoughtList(m);
				// 获取集中学习的总分
				int thoughtscore = 0;
				if (listthought != null) {
					for (Map<String, Object> map : listthought) {
						thoughtscore += (int) map.get("score");
						// 写入月度考核的总结summary
						monthtest.setSummary(map.get("content").toString());
					}
				}
				logger.info("thoughtscore=" + thoughtscore);
				// 根据pid和月份查找加分扣分管理的加分列表
				List<Map<String, Object>> listbonus = monthtestservice.selectBonusList(m);
				// 获取加分的总分
				Double bonusscore = 0.0;
				for (Map<String, Object> map : listbonus) {
					bonusscore += (Double) map.get("point");
				}
				logger.info("bonusscore=" + bonusscore);
				// 根据pid和月份查找加分扣分管理的扣分列表
				List<Map<String, Object>> listpoint = monthtestservice.selectPointsList(m);
				// 获取扣分的总分
				Double pointscore = 0.0;
				for (Map<String, Object> map : listpoint) {
					pointscore += (Double) map.get("point");
				}
				logger.info("pointscore=" + pointscore);
				// 考核总得分
				Double x = labourscore + thoughtscore + reportscore + bonusscore - pointscore;
				logger.info("x=" + x);

				Double xy = x - times * 10.0;
				logger.info("xy=" + xy);
				// 生成该月度考核记录
				if (listlabour != null || listreport != null || listthought != null) {
					monthtest.setMonth(sdf.format(new Date()));
					monthtest.setOpinion("待提交");
					monthtest.setPid(correctedPerson.getId());
					monthtest.setPoints(x);
					monthtest.setBasicpoints(times * 10.0);
					if (xy >= 3) {// 当加分大于等于3分且扣分小于等于0分
						monthtest.setLevel("优秀");
					} else if (xy < 3 && xy >= 0) {// 当加分小于3分且大于0分,扣分小于等于0分
						monthtest.setLevel("良好");
					} else if (xy < 0 && xy >= -3) {// 当扣分小于等于3分,且扣分大于0分;
						monthtest.setLevel("一般");
					} else {
						monthtest.setLevel("差");
					}
					monthtestservice.addMonthTest(monthtest);
				}
			}
		}
	}

	/**
	 * 导出Excel
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "exportExcel")
	public String download(int[] id, HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 生成选择项的导出list
		List<Map<String, Object>> projects = new ArrayList<Map<String, Object>>();
		if (id != null) {
			MonthTest monthtest = new MonthTest();
			for (int i : id) {
				logger.info("批量导出月度考核id=" + i);
				monthtest.setId(i);
				Map<String, Object> m = monthtestservice.getMonthTestById(monthtest);
				projects.add(m);
			}
		} else {
			projects = createData();
		}

		String fileName = "月度考核记录excel文件";
		List<Map<String, Object>> list = createExcelRecord(projects);
		String columnNames[] = { "序号", "矫正单位", "矫正人员", "考核月份", "考核得分", "考核等级", "个人小结", "考核意见" };// 列名
		String keys[] = { "id", "jname", "cname", "month", "points", "level", "summary", "opinion" };// map中的key
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			ExcelUtil.createWorkBook(list, keys, columnNames).write(os);
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] content = os.toByteArray();
		InputStream is = new ByteArrayInputStream(content);
		// 设置response参数，可以打开下载页面
		response.reset();
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		response.setHeader("Content-Disposition",
				"attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
		ServletOutputStream out = response.getOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			// Simple read/write loop.
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (final IOException e) {
			throw e;
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}
		return null;
	}

	private List<Map<String, Object>> createData() {
		// TODO Auto-generated method stub
		List<Map<String, Object>> list = monthtestservice.getAllMonthTest();
		return list;
	}

	private List<Map<String, Object>> createExcelRecord(List<Map<String, Object>> projects) {
		List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("sheetName", "sheet1");
		listmap.add(map);
		Map<String, Object> object = null;
		for (int j = 0; j < projects.size(); j++) {
			object = projects.get(j);
			Map<String, Object> mapValue = new HashMap<String, Object>();
			mapValue.put("id", object.get("id"));
			mapValue.put("jname", object.get("jname"));
			mapValue.put("cname", object.get("cname"));
			mapValue.put("month", object.get("month"));
			mapValue.put("points", object.get("points"));
			mapValue.put("level", object.get("level"));
			mapValue.put("summary", object.get("summary"));
			mapValue.put("opinion", object.get("opinion"));
			listmap.add(mapValue);
		}
		return listmap;
	}

}
